package org.xtframe.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jbpm.api.ProcessDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.xtframe.entity.UserData;
import org.xtframe.service.AjaxDataHandler;
import org.xtframe.service.AjaxDataHandlerException;
import org.xtframe.util.ContextUtil;
import org.xtframe.util.JbpmUtil;

@Service
@Scope("prototype")
public class ProcessDefinitionListDataHandler implements AjaxDataHandler {

	private final Log logger = LogFactory.getLog(getClass());

	public Map<String, Object> execute(String strData) {
		Map<String, Object> map = new HashMap<String, Object>();
		
		try {
			UserData userData = ContextUtil.getCurrentUserData();
			if(userData == null){
				map.put(STATUS, false);
				map.put(LOGIN, true);
				throw new AjaxDataHandlerException("未登陆执行获取流程定义列表", 1);
			}
			
			List<ProcessDefinition> pdList = JbpmUtil.getInstance().getAllProcessDefinitionList();
			List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
			Map<String, Object> row = null;
			int columnCount = 4;	//预定列的数目
			for (ProcessDefinition pd : pdList) {
				row = new HashMap<String, Object>(columnCount);
				row.put("id", pd.getId());
				row.put("deploymentId", pd.getDeploymentId());
				row.put("name", pd.getName());
				row.put("version", pd.getVersion());
				rows.add(row);
			}
			map.put(STATUS, true);
			map.put(LIST, rows);
		} catch(AjaxDataHandlerException ex){
			logger.warn(ex.toString());
			if(ex.getFlag() == 0){
				map.clear();
				map.put(STATUS, false);
			}
		} catch (Exception e) {
			logger.error(e.toString());
			map.clear();
			map.put(STATUS, false);
		}
		
		return map;
	}

}
